# I still suck at Makefiling

LIB = nspiregamekit

OBJS  = screen.o nimg.o gameloop.o autorelease.o text.o 
OBJS += optimized.o random.o objects.o collision.o debugc.o 
OBJS += debugasm.o types.o file.o timer.o ndlesscpp.o

EXAMPLEOBJS = test.o ndlesscpp.o
EXAMPLE = test

DISTDIR = ./example
LIBDIR = ./lib

GCC = nspire-gcc
GPP = nspire-g++
LD = nspire-ld
GCCFLAGS = -funroll-loops -Wall -W -I./include -fno-rtti
LDFLAGS =  -Wl,--emit-reloc -L$(LIBDIR) -l$(LIB) -lndls -lgcc
OBJCOPY := "$(shell which arm-elf-objcopy 2>/dev/null)"
AR := "$(shell which arm-elf-ar 2>/dev/null)"
ifeq (${OBJCOPY},"")
	OBJCOPY := arm-none-eabi-objcopy
endif
ifeq (${AR},"")
	AR := arm-none-eabi-ar
endif

vpath %.tns $(DISTDIR)

all:
	@echo \#\#\#\# Building lib$(LIB) \#\#\#\#
	@make lib
	@echo \#\#\#\# Building Example \#\#\#\#
	@make example

%.o: %.c
	$(GCC) $(GCCFLAGS) -c $<
	
%.o: %.cpp
	$(GPP) $(GCCFLAGS) -c $<

%.o: %.S
	$(GCC) $(GCCFLAGS) -c $<
	
lib: $(OBJS)
	mkdir -p $(LIBDIR)
	$(AR) rcs $(LIBDIR)/lib$(LIB).a $(OBJS)


example: lib $(EXAMPLEOBJS)
	$(LD) $(EXAMPLEOBJS) -o $(EXAMPLE).elf $(LDFLAGS)
	mkdir -p $(DISTDIR)
	cp $(EXAMPLE).elf $(DISTDIR)/$(EXAMPLE).elf.tns
	$(OBJCOPY) -O binary $(EXAMPLE).elf $(DISTDIR)/$(EXAMPLE).tns

clean:
	rm -f *.o *.elf *.a
	rm -f $(DISTDIR)/$(EXAMPLE)
	rm -f $(LIBDIR)/lib$(LIB).a
